<template>
  <div>
    <button type="button" @click="selectFile()" class="btn btn-white btn-default btn-round">
      <i class="ace-icon fa fa-upload"></i>
      {{ text }}
    </button>
    <input class="hidden" ref="file" type="file" @change="uploadFile()" id="file-upload-input">
  </div>
</template>

<script>
  export default {
    name: 'pagination',
    props: {
      text: {
        default: '上传文件',
      },
      inputId: {
        default: 'file-upload'
      },
      suffixs: {
        default: []
      },
      use: {
        default: ""
      },
      afterUpload: {
        type: Function,
        default: null
      }
    },
    data: function () {
      return {
      }
    },
    methods: {
      uploadFile() {
        let _this = this;
        let formData = new window.FormData;
        let file = _this.$refs.file.files[0];
        // 判断文件格式
        let suffixs = _this.suffixs;
        let filename = file.name;
        let suffix = filename.substring(filename.lastIndexOf(".") + 1, filename.length).toLowerCase();
        let validateSuffix = false;
        for (let i = 0; i < suffixs.length; i++) {
          if (suffixs[i].toLowerCase() === suffix) {
            validateSuffix = true;
            break
          }
        }
        if (!validateSuffix) {
          Toast.warning("文件格式不正确! 只支持上传: " + suffixs.join(","));
          $("#" + _this.inputId + "-input").val("");
          return;
        }
        // key:"file" 必须和后端 controller 参数一致
        formData.append('file', file);
        formData.append('use', _this.use);
        Loading.show();
        _this.$postForm(process.env.VUE_APP_SERVER + "/file/admin/upload/", formData).then(res => {
          Loading.hide();
          console.log(res);
          _this.afterUpload(res);
        }).catch(res => {
          Loading.hide();
          console.log(res);
          Toast.error('上传失败！')
        });
      },
      selectFile(){
        let _this = this;
        $("#" + _this.inputId + "-input").trigger('click');
      }
    }
  }
</script>

<style scoped>

</style>
